<?php
/**
 * String util
 * @author Anh Tu Ngo
 * @date 12/03/2011
 */
final class String {

	/**
	 * Enter description here ...
	 * @param string $str
	 * @return boolean
	 */
	public static function isEmpty($str) {
		return $str == '' || $str == null;
	}

	/**
	 * Random string
	 * @param number $lenght
	 * @return string
	 */
	public static function random($lenght = 8) {
		$time = microtime();
		return strtoupper(substr(md5("random($time)"), 0, $lenght));
	}

	/**
	 * Add space to any charactor
	 * @param string $string
	 * @return string
	 */
	public static function addSpace($string) {
		$str = '';

		for ($i = 0; $i < strlen($string); $i ++) {
			$str .= ($i > 0 ? ' ' : '') . $string[$i];
		}

		return $str;
	}

	/**
	 * MD5 encoding
	 * @param string $string
	 * @return string
	 */
	public static function md5($string) {
		return md5("md5($string);");
	}

	/**
	 * Replace string with a charactor
	 * @param string $string
	 * @param char $char
	 * @param number $beginIndex
	 * @return string
	 */
	public static function replaceWith($string, $char, $beginIndex = 0) {
		$str = $string;

		$len	= strlen($string);
		if ($len > $beginIndex) {
			$str = substr($string, 0, $beginIndex);
			for ($i = $beginIndex; $i < $len; $i++)
			$str .= $char;
		}

		return $str;
	}

	public static function wrap($str, $limit = 10) {
		$str = strip_tags($str);
		$strNext = " ...";
		$array = str_word_count(strip_tags($str), 1, '0..3');

		if (sizeof($array) <= $limit) {
			$limit = sizeof($array);
			$strNext = "";
		}

		$str = '';
		for ($i = 0; $i < $limit; $i++) {
			$str .= ' ' . $array[$i];
		}
		return $str . $strNext;
	}

	public static function firstWork($str) {
		$array =  preg_split("/\s+/", $str);
		foreach ($array as $work) {
			if (sizeof($work) > 0 && $work != ' ') {
				return $work;
			}
		}
		return null;
	}

	/**
	 * Remove Unicode
	 * @param string $str
	 */
	public static function filter ($str){
		$unicode = array(
            'a'=>'Ã¡|Ã |áº£|Ã£|áº¡|Äƒ|áº¯|áº·|áº±|áº³|áºµ|Ã¢|áº¥|áº§|áº©|áº«|áº­',
            'd'=>'Ä‘',
            'e'=>'Ã©|Ã¨|áº»|áº½|áº¹|Ãª|áº¿|á»�|á»ƒ|á»…|á»‡',
            'i'=>'Ã­|Ã¬|á»‰|Ä©|á»‹',
            'o'=>'Ã³|Ã²|á»�|Ãµ|á»�|Ã´|á»‘|á»“|á»•|á»—|á»™|Æ¡|á»›|á»�|á»Ÿ|á»¡|á»£',
            'u'=>'Ãº|Ã¹|á»§|Å©|á»¥|Æ°|á»©|á»«|á»­|á»¯|á»±',
            'y'=>'Ã½|á»³|á»·|á»¹|á»µ',
			'A'=>'Ã�|Ã€|áº¢|Ãƒ|áº |Ä‚|áº®|áº¶|áº°|áº²|áº´|Ã‚|áº¤|áº¦|áº¨|áºª|áº¬',
            'D'=>'Ä�',
            'E'=>'Ã‰|Ãˆ|áºº|áº¼|áº¸|ÃŠ|áº¾|á»€|á»‚|á»„|á»†',
            'I'=>'Ã�|ÃŒ|á»ˆ|Ä¨|á»Š',
            'O'=>'Ã“|Ã’|á»Ž|Ã•|á»Œ|Ã”|á»�|á»’|á»”|á»–|á»˜|Æ |á»š|á»œ|á»ž|á» |á»¢',
            'U'=>'Ãš|Ã™|á»¦|Å¨|á»¤|Æ¯|á»¨|á»ª|á»¬|á»®|á»°',
            'Y'=>'Ã�|á»²|á»¶|á»¸|á»´',
		);

		foreach($unicode as $nonUnicode=>$uni){
			$str = preg_replace("/($uni)/i", $nonUnicode, $str);
		}
		return $str;
	}
}
?>